import { defineStore } from 'pinia'
import { useLocalStorage } from '@vueuse/core'
import { store } from '../'
import useHttp, { useLocalHttp } from '@renderer/utils/http'
import GoldIcon from '@renderer/assets/huangjin.svg'
import PlatinumIcon from '@renderer/assets/bojin.svg'
import MasonryIcon from '@renderer/assets/zuanshi.svg'
import KingIcon from '@renderer/assets/wangzhe.svg'
import NetDiscountIcon from '@renderer/assets/netDiscount.svg'
import VipActivityIcon from '@renderer/assets/vipActivity.svg'
import BirthdayIcon from '@renderer/assets/birthday.svg'
// import KeepSeatIcon from '@renderer/assets/keepSeat.svg'
import NetDiscountIconInner from '@renderer/assets/netDiscountInner.svg'
import VipActivityIconInner from '@renderer/assets/vipActivityInner.svg'
import BirthdayIconInner from '@renderer/assets/birthdayInner.svg'
// import KeepSeatIconInner from '@renderer/assets/keepSeatInner.svg'
import dayjs from 'dayjs'
import { transformNo } from '@renderer/utils/http'
const storageKey = 'yydj'
const ACCESS_TOKEN = 'ACCESS-TOKEN'
const CURRENT_USER = 'CURRENT-USER'
const RANDOM_AVATAR_URL = 'https://api.multiavatar.com/'
const storage = useLocalStorage(storageKey, {
  [ACCESS_TOKEN]: null,
  [CURRENT_USER]: {}
})
let timer: null | number = null
const tasks = []
export interface IUserState {
  // 用户身份标识
  token: string
  // 用户昵称
  username: string
  // 用户头像
  avatar: string
  // 用户基本信息
  info: any
  // 二维码图片地址
  url: null | string
  // 获取登录吗和轮询登录的场景码
  state: string
  // 登录窗口的状态（开启或者关闭）
  pending: false
  // 登录成功
  status: string
  // 用户会员等级
  level: null | number
  // 会员等级信息
  vipInfo: any
  // 权益信息
  powerInfo: any
  couponType: any
  coupons: any[]
}
export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: storage.value[ACCESS_TOKEN],
    username: '',
    avatar: '',
    info: storage.value[CURRENT_USER],
    url: null,
    state: '',
    pending: false,
    status: 'pending',
    vipInfo: [],
    coupons: [],
    couponType: [
      {
        label: '商品券',
        value: 1
      },
      {
        label: '充值券',
        value: 2
      },
      {
        label: '上网券',
        value: 3
      },
      {
        label: '酒店券',
        value: 4
      },
      {
        label: '麻将券',
        value: 5
      },
      {
        label: '台球券',
        value: 6
      }
    ],
    powerInfo: [
      {
        icon: NetDiscountIcon,
        innerIcon: NetDiscountIconInner,
        name: '上网折扣',
        content: '9.5折'
      },
      {
        icon: VipActivityIcon,
        innerIcon: VipActivityIconInner,
        name: '充送优惠',
        content: '专享充送优惠'
      },
      {
        icon: BirthdayIcon,
        innerIcon: BirthdayIconInner,
        name: '生日特权',
        content: '当天上网免费'
      }
      // {
      //   icon: KeepSeatIcon,
      //   innerIcon: KeepSeatIconInner,
      //   name: '订座保留',
      //   content: '额外免费30分钟'
      // }
    ]
  }),
  getters: {
    level() {
      return this.info?.level
    },
    openLevelTime() {
      return this.info?.openLevelTime
    },
    levelTimeout() {
      if (this.openLevelTime) {
        const year = dayjs(this.openLevelTime).year()
        return dayjs(this.openLevelTime)
          .set('year', Number(year) + 1)
          .format('YYYY-MM-DD')
      }
      return null
    },
    GetPending() {
      return this.pending
    },
    GetToken(): string | null {
      return this.token
    },
    GetUserName(): string {
      return this.username || this.info?.name
    },
    GetAvatar(): string {
      return (
        this.avatar ||
        this.info?.avatar ||
        `${RANDOM_AVATAR_URL}${this.GetUserName?.split('@')[1]}.png`
      )
    },
    GetInfo(): any {
      return this.info
    }
  },
  actions: {
    setToken(token: string) {
      storage.value[ACCESS_TOKEN] = token
      this.token = token
    },
    setUserInfo(info: any) {
      storage.value[CURRENT_USER] = info
      this.info = info
    },
    setUserName(name: string) {
      this.username = name
    },
    setAvatar(avatar: string) {
      this.avatar = avatar
    },
    setState(state: string) {
      this.state = state
    },
    /**
     * 全局唤醒或者关闭登录
     * 1. 如果是关闭登录，清空所有的任务
     * 2. 如果是开启登录，则把任务加入到队列里面
     */
    invokeLogin(status: boolean, task?: any) {
      if (task) {
        tasks.push(task)
      }
      if (!status) {
        tasks.splice(0, tasks.length)
      }
      this.pending = status
    },
    /**
     * 获取到登录图片
     */
    async getTicket() {
      const { data } = await useHttp(`/wx/ticket?sceneStr=${this.state}`).get().json()
      if (data.value.code === 200) {
        this.url = data.value.data.imgUrl
      }
    },
    /**
     * 轮询登录
     * 登录成功后，执行队列里面的任务并清空
     */
    async login(cb?: any) {
      timer = setInterval(async () => {
        // 获取登录是否成功
        const { data: d } = await useHttp(`/user/wxCommonLogin?state=${this.state}`).get().json()
        if (d.value.code === 200) {
          clearInterval(timer as number)
          timer = null
          this.setToken(d.value.data.token)
          // 获取用户信息
          const { data: userInfo } = await useHttp(`/user/info`).get().json()
          this.setUserInfo({
            name: userInfo.value.data.name,
            avatar: userInfo.value.data.headimgurl,
            token: userInfo.value.data.token,
            level: userInfo.value.data.level_id,
            openLevelTime: userInfo.value.data.open_level_time
          })
          this.setUserName(userInfo.value.data.name)
          // 清空任务队列
          while (tasks.length) {
            const task = tasks.pop()
            task()
          }
          cb && cb()
        }
      }, 2000)
    },
    /**
     * 登出 清空
     */
    loginout() {
      storage.value = {}
      this.info = null
      this.username = null
      this.avatar = null
      this.token = null
      this.tasks = []
      this.stats = null
      this.url = null
      this.pending = false
    },
    /**
     * 更改登录成功状态
     */
    changeStatus(status) {
      this.status = status
    },
    // 获取会员列表
    async getLevelList() {
      const { data: res } = await useHttp('/level/c/list').get().json()
      if (res.value.code === 200) {
        this.vipInfo = res.value.data.map((level) => {
          if (level.icon === 'GoldIcon') {
            level.icon = GoldIcon
          } else if (level.icon === 'PlatinumIcon') {
            level.icon = PlatinumIcon
          } else if (level.icon === 'MasonryIcon') {
            level.icon = MasonryIcon
          } else if (level.icon === 'KingIcon') {
            level.icon = KingIcon
          }
          return level
        })
      }
    },
    // 设置会员等级
    /**
     *       {
        icon: GoldIcon,
        name: '黄金会员',
        en: 'Gold Members',
        discount: 9.5,
        price: 99,
        id: 1,
        coupons: [
          {
            type: '充值券',
            content: '送1张"充50送30元充值卷"',
            single: 30,
            number: 1
          },
          {
            type: '每月充值优惠',
            content: '送3张"充100送30元充值卷"',
            single: 30,
            number: 3
          },
          {
            type: '饮品半价券',
            content: '送3张饮品半价劵，每张优惠金额约10元',
            single: 30,
            number: 3
          },
          {
            type: '通宵半价券',
            content: '送3张通宵半价劵，每张优惠金额约20元',
            single: 20,
            number: 3
          }
        ],
        theme: '#F5AE4C',
        bg: '#FFF4CB'
      },
     */
    async setLevel() {
      const { data: res } = await useHttp('/level/c/list').get().json()
      if (res.value.code === 200) {
        console.log(res.value.data)
      }
    },
    async openLevel(
      levelId: number,
      levelName?: string,
      storeName?: string | null,
      no?: string | null,
      card?: string
    ) {
      const { data: res } = await useHttp(`/user/openLevel`)
        .post({
          levelId,
          card
        })
        .json()
      if (res.value.code === 200) {
        // 发送消息到前台
        useLocalHttp('/print').post({
          no: transformNo(no),
          store: storeName,
          type: 'openLevel',
          data: [
            {
              levelName,
              card
            }
          ]
        })
        // 设置用户等级
        const { data: userInfo } = await useHttp(`/user/info`).get().json()
        this.setUserInfo({
          name: userInfo.value.data.name,
          avatar: userInfo.value.data.headimgurl,
          token: userInfo.value.data.token,
          level: userInfo.value.data.level_id,
          openLevelTime: userInfo.value.data.open_level_time
        })
        this.setUserName(userInfo.value.data.name)
      }
    },
    // 获取优惠券
    async setCoupon(type: number | null) {
      const url = type ? `/user/c/userCoupon?type=${type}` : '/user/c/userCoupon'
      const { data: res } = await useHttp(url).get().json()
      if (res.value.code === 200) {
        this.coupons = res.value.data
          .filter((coupon) => coupon.userCoupons?.is_delete == 0 && coupon.userCoupons?.total)
          .map((coupon) => {
            const {
              type,
              recharge_fee,
              give_fee,
              discount_condition_match,
              discount_condition_minus,
              discount_type,
              discount_number,
              discount_index,
              validity_end,
              validity_type,
              validity_day,
              userCoupons,
              poster
            } = coupon

            return {
              ...coupon,
              label: this.couponType.find((couponType) => couponType.value === type)?.label,
              url: JSON.parse(poster || '[]')?.[0]?.url,
              condition:
                type === 1
                  ? discount_condition_match
                    ? `满${discount_condition_match}`
                    : '无门槛'
                  : type === 2
                  ? `充值${recharge_fee}`
                  : type === 5
                  ? '多功能室'
                  : type === 4
                  ? '电竞酒店'
                  : type === 6
                  ? '台球室'
                  : '通宵上网',
              money:
                discount_type === 1
                  ? `减_${discount_condition_minus}`
                  : discount_type === 2
                  ? `抵扣_${discount_number}`
                  : discount_type === 3
                  ? `$折_${discount_index}`
                  : discount_type === 4
                  ? `送_${give_fee}`
                  : '$折_5',
              img: '',
              isAccumulate: false,
              timeout:
                validity_type === 1
                  ? dayjs(new Date(validity_end)).format('YYYY.MM.DD')
                  : dayjs(new Date(userCoupons.create_at))
                      .add(validity_day, 'day')
                      .format('YYYY.MM.DD')
            }
          })
      }
    }
  }
})

export function useUserStoreWidthOut() {
  return useUserStore(store)
}
